package com.xj.community.controller;

import com.xj.community.Service.FollowService;
import com.xj.community.Service.LikeService;
import com.xj.community.Service.UserService;
import com.xj.community.annotation.RequiredLogin;
import com.xj.community.entity.User;
import com.xj.community.util.CommunityConstant;
import com.xj.community.util.CommunityUtil;
import com.xj.community.util.MyThreadLocal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Controller
@RequestMapping("/user")
public class UserController implements CommunityConstant {
    @Autowired
    private UserService userService;

    @Autowired
    private LikeService likeService;

    @Autowired
    private FollowService followService;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Value("${community.path.upload}")
    private String upload;

    //获取设置用户信息页面
    @RequiredLogin
    @RequestMapping(path = "/setting",method = RequestMethod.GET)
    public String settingPage(){
        return "/site/setting";
    }

    //上传用户头像
    @RequiredLogin
    @RequestMapping(path = "/upload",method = RequestMethod.POST)
    public String upload(MultipartFile multipartFile, Model model){
        if(multipartFile == null){
            model.addAttribute("error","图片不能为空");
            return "/site/setting";
        }
        String originalFilename = multipartFile.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if(suffix==null || !(suffix.equals(".jpeg") || suffix.equals(".jpg") || suffix.equals(".png"))){
            model.addAttribute("error","文件格式错误，请重新上传");
            return "/site/setting";
        }
        //生成文件名
        User user = MyThreadLocal.getUser();
        String fileName =upload + "/" + user.getUsername() + suffix;
        //将图片存储到硬盘中
        File file = new File(fileName);
        try {
            multipartFile.transferTo(file);
        } catch (IOException e) {
            e.printStackTrace();
        }

        //更新用户头像的url
        String headerUrl = domain +  contextPath + "/user/upload/" + user.getUsername()+suffix;
        userService.updateHead(user.getId(),headerUrl);
        return "redirect:/index";
    }

    //返回用户头像请求
    @RequestMapping(path = "/upload/{fileName}",method = RequestMethod.GET)
    public void getHeader(@PathVariable("fileName") String fileName, HttpServletResponse response){
        //服务器存放图片的路径
        String path = upload + "/" + fileName;
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        //响应图片
        response.setContentType("image/"+suffix);
        FileInputStream fileInputStream = null;
        OutputStream outputStream = null;
        try {
            fileInputStream = new FileInputStream(path);
            outputStream = response.getOutputStream();
            byte[] bytes = new byte[1024];
            int length = 0;
            while((length = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes,0,length);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fileInputStream != null){
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    //修改密码
    @RequiredLogin
    @RequestMapping(path = "/changePwd",method = RequestMethod.POST)
    public String changePwd(HttpServletRequest request,Model model){
        String oldPwd = request.getParameter("old");
        String newPwd = request.getParameter("new");
        User user = MyThreadLocal.getUser();
        String originalPwd = user.getPassword();
        //检查输入的原密码是否正确
        if(!originalPwd.equals(CommunityUtil.md5(oldPwd+user.getSalt()))){
            model.addAttribute("errorPwd","密码输入错误");
            return "/site/setting";
        }
        //将密码修改为新密码
        userService.updatePwd(user.getId(),CommunityUtil.md5(newPwd+user.getSalt()));
        return "redirect:/logout";
    }

    // 个人主页
    @RequestMapping(path = "/profile/{userId}", method = RequestMethod.GET)
    public String getProfilePage(@PathVariable("userId") int userId, Model model) {
        User user = userService.selectById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }

        // 用户
        model.addAttribute("user", user);
        // 点赞数量
        int likeCount = likeService.findUserLikeCount(userId);
        model.addAttribute("likeCount", likeCount);

        // 关注数量
        long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);
        model.addAttribute("followeeCount", followeeCount);
        // 粉丝数量
        long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);
        model.addAttribute("followerCount", followerCount);
        // 是否已关注
        boolean hasFollowed = false;
        if (MyThreadLocal.getUser() != null) {
            hasFollowed = followService.hasFollowed(MyThreadLocal.getUser().getId(), ENTITY_TYPE_USER, userId);
        }
        model.addAttribute("hasFollowed", hasFollowed);


        return "/site/profile";
    }
}
